<template>
    <AbsoluteContainer>
        <page-header title="资讯管理" />
        <page-main>
            <!-- 数据列表 -->
            <el-table :data="dataList" border stripe highlight-current-row height="250">
                <el-table-column label="序号" width="50" align="center">
                    <template scope="scope"><span>{{ scope.$index+(page - 1) * pageSize + 1 }} </span></template>
                </el-table-column>
                <el-table-column prop="title" label="标题" width="100" />
                <el-table-column label="标题图片" width="150">
                    <template slot-scope="scope">
                        <el-image slot="reference" :src="scope.row.titleimg" style="width: 100px; height: 80px;" fit="scale-down" />
                    </template>
                </el-table-column>
                <el-table-column prop="onshelf" label="上架状态" width="100" :formatter="tt" />
                <el-table-column :show-overflow-tooltip="true" prop="type" label="一级分类" width="100" />
                <el-table-column :show-overflow-tooltip="true" prop="intype" label="二级分类" width="100" />
                <el-table-column :show-overflow-tooltip="true" prop="stype" label="三级分类" width="100" />
                <el-table-column prop="instay" label="浏览量" width="100" />
                <el-table-column :show-overflow-tooltip="true" prop="url" label="网页链接" width="100" />
                <el-table-column prop="crad" label="测验题名称" width="100" />
                <el-table-column :show-overflow-tooltip="true" prop="pdf" label="pdf" width="100" />
                <el-table-column prop="integral" label="积分" width="100" />
                <el-table-column prop="shelfofftime" label="资讯结束日期" width="100" />
                <!-- 操作框(编辑和删除) -->
                <el-table-column fixed="right" label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="upd(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="_delete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                background=""
                :current-page="page"
                :page-size="pageSize"
                layout="total,  prev, pager, next, jumper"
                :total="total"
                @current-change="handleCurrentChange"
            />
        </page-main>
    </AbsoluteContainer>
</template>

<script>
export default {
    name: 'ComponentExampleAbsoluteContainer',
    props: {},
    data() {
        return {
            classInfo: [], // 页面数据
            dataList: [], // 当前显示的页面数据
            selectionDataList: [],
            total: null, // 总共多少条数据
            page: 1, // 当前页数
            pageSize: 5, // 每页显示多少条数据
            searchId: '', // 查询ID
            searchResult: [], // 搜索显示的数据
            searchName: '', // 搜索的昵称
            searchPhone: ''// 搜索的手机号码
        }
    },
    created() {
        // 调用获取数据函数
        this.listAllBlog()
    },
    methods: {
        // 查询
        search() {
            const valueInput = this.searchName
            // const phoneInput = this.searchPhone
            this.searchResult = this.classInfo.filter(item => {
                if (item.nickName.includes(valueInput)) {
                    return item
                }
            })

        },
        // 审核状态格式化
        ckFormat(row) {
            let ck = row.ck
            if (ck == '1') {
                return '未通过'
            } else if (ck == '2') {
                return '已通过'
            } else if (ck == '3') {
                return '已离职'
            } else {
                return '审核中'
            }
        },
        // 邮箱格式化
        emailFormat(row) {
            return row.emailreg ? '已认证' : '未认证'
        },
        // 获取数据
        async listAllBlog() {
            const app = this.$cloudbase.init({
                env: 'club-0g3m1vfs8f5ebda5'
            })
            await app.auth({
                persistence: 'local'
            }).signInWithEmailAndPassword('liweicon0917@sina.com', 'liweicon1')
                .then(() => {
                    let that = this
                    const db = app.database()
                    const userDb = db.collection('information')
                    userDb.get().then(item => {
                        // const urlReg = /cloud/
                        // if (urlReg.test(item.data[i].titleimg)) {
                        //     const http = 'https://636c-club-0g3m1vfs8f5ebda5-1303170401.tcb.qcloud.la/cloudbase-cms/upload'
                        //     const url = item.data[i].titleimg.split('upload')[1]
                        //     item.data[i].titleimg = http + url
                        // }
                        const http = 'https://636c-club-0g3m1vfs8f5ebda5-1303170401.tcb.qcloud.la/cloudbase-cms/upload'
                        const url =  item.data[1].titleimg[0].split('upload')[1]
                        item.data[1].titleimg = http + url
                        // console.log(item.data[i])

                        that.classInfo = item.data
                        that.total = that.classInfo.length
                        this.setCurrentPageData()
                        console.log(that.classInfo)
                    }
                    )
                }).catch(error => {
                    console.log('登录失败', error)
                })

        },
        // 添0占位
        formatTen(num) {
            return num > 9 ? (num + '') : ('0' + num)
        },
        // 标准时间转年月日时分秒
        timeFormat(timeFormat) {
            var date = new Date(timeFormat)
            var year = date.getFullYear()
            var month = date.getMonth() + 1
            var day = date.getDate()
            var hour = date.getHours()
            var minute = date.getMinutes()
            var second = date.getSeconds()
            return year + '-' + this.formatTen(month) + '-' + this.formatTen(day) + ' ' + this.formatTen(hour) + ':' + this.formatTen(minute) + ':' + this.formatTen(second)
        },
        // 时间戳转换为年月日时分秒
        timestampToTime(value) {
            if (typeof (value) == 'undefined') {
                return ''
            } else {
                let date = new Date(parseInt(value))
                let y = date.getFullYear()
                let MM = date.getMonth() + 1
                MM = MM < 10 ? ('0' + MM) : MM
                let d = date.getDate()
                d = d < 10 ? ('0' + d) : d
                let h = date.getHours()
                h = h < 10 ? ('0' + h) : h
                let m = date.getMinutes()
                m = m < 10 ? ('0' + m) : m
                let s = date.getSeconds()
                s = s < 10 ? ('0' + s) : s
                return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
            }
        },
        // 跳转至编辑页面
        upd(row) {
            let routerName
            routerName = 'componentExtendExampleUserupdate'
            this.$router.push({
                name: routerName,
                params: {
                    id: row._id,
                    nickName: row.nickName,
                    avatarUrl: row.avatarUrl,
                    allintegral: row.allintegral,
                    integral: row.integral,
                    openid: row._openid,
                    logtime: row.logtime,
                    company: row.company,
                    ck: row.ck,
                    email: row.email,
                    partners: row.partners,
                    phone: row.phone,
                    emailreg: row.emailreg
                }
            })
        },
        // 跳转至新建页面
        add() {
            let routerName
            routerName = 'componentExtendExampleUseradd'
            this.$router.push({
                name: routerName
            })
        },
        // 上架显示true和false的回调
        tt(cellValue) {
            return cellValue.onshelf ? 'True' : 'False'

        },
        // 刷新页面
        refresh() {
            this.listAllBlog()
        },
        // 删除数据
        async _delete(row) {
            const confirmResult = await this.$confirm('确认删除此内容?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            /* 如果用户确认打印confirm,如果用户取消显示cancel*/
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除!')
            }
            const user = this.$cloudbase.database().collection('user')
            user.doc(row._id)
                .remove()
                .then(
                    this.listAllBlog()
                )
                .catch(err => {
                    console.log(err)
                })

        },
        // 设置当前页面分页
        setCurrentPageData() {
            let begin = (this.page - 1) * this.pageSize
            let end = this.page * this.pageSize
            this.dataList = this.classInfo.slice(
                begin,
                end
            )
        },
        // 当当前页改变
        handleCurrentChange(val) {
            if (this.Page == this.total) return
            console.log(`当前页: ${val}`)
            console.log(val)
            this.page = val
            this.setCurrentPageData()
        }

    }

}

</script>

<style lang="scss" scoped>
.page-main {
    display: flex;
    flex-direction: column;

    // 减去的 40px 为 page-main 的上下 margin
    // 减去的 130px 为 page-header 的高度，如果没有设置，可以去掉

    height: calc(100% - 40px - 60px);
    ::v-deep .el-table {
        height: 100%;
        .el-table__body-wrapper {
            overflow-y: auto;
        }
    }
}
.mainBtn {
    display: flex;
    justify-content: flex-end;
    margin: 0 20px;
}
.mainBtn .addBtn {
    margin: 10px 10px;
    width: 100px;
}

</style>
